import type { LoginResult } from '@/types'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useMemberStore = defineStore(
  'member',
  () => {
    /** 会员信息 */
    const profile = ref<LoginResult>()
    /** 会员是否已登录 */
    const isLogin = computed(() => Boolean(profile.value?.token))

    /**
     * 登录时保存会员信息
     * @param val
     */
    const setProfile = (val: LoginResult) => {
      profile.value = val
    }

    /**
     * 退出时清理会员信息
     */
    const clearProfile = () => {
      profile.value = undefined
    }

    /**
     * 更新会员头像
     * @param path 图片路径
     */
    const updateProfileAvatar = (path: string) => {
      profile.value!.avatar = path
    }

    /**
     * 更新会员昵称
     * @param val 昵称
     */
    const updateProfileNickname = (val: string) => {
      profile.value!.nickname = val
    }

    return {
      profile,
      isLogin,
      setProfile,
      clearProfile,
      updateProfileAvatar,
      updateProfileNickname,
    }
  },
  {
    persist: true,
  },
)
